<?php
declare(strict_types=1);

namespace Zlf\AppHyperfCasts;

use Hyperf\Contract\CastsAttributes;
use Hyperf\Database\Query\Expression;
use Hyperf\DbConnection\Db;


/**
 * 坐标位置储存,适用于mysql8
 */
class StPointCasts implements CastsAttributes
{
    /**
     * 获取结果
     */
    public function get($model, $key, $value, $attributes): array
    {
        $default = ['lng' => '', 'lat' => ''];
        if (gettype($value) === 'string' && $value) {
            $data = unpack('x/x/x/x/corder/Ltype/dlon/dlat', $value);
            if (isset($data['lat']) && isset($data['lon'])) {
                return ($data['lat'] && $data['lon']) ? ['lat' => $data['lat'], 'lng' => $data['lon']] : $default;
            }
        }
        return $default;
    }

    /**
     * 设置数据
     * @return Expression|array|string|null
     */
    public function set($model, $key, $value, $attributes)
    {
        if (is_array($value) && isset($value['lng']) && isset($value['lat'])) {
            if ($value['lng'] && $value['lat']) {
                return DB::raw("ST_GeomFromText('POINT({$value['lng']} {$value['lat']})')");
            }
        }
        return null;
    }
}
